package com.janwen.spring.trx.declarative;

import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
@Service("defaultService")
public class DefaultFooService implements FooService {
     
	@Autowired
	private DataSource dataSource;
	

	static final Log logger = LogFactory.getLog(DefaultFooService.class);
	@Override
	public Foo getFoo(String fooName) {
		String sql = "SELECT * FROM stuff WHERE name=?";
		JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
		List<Map<String,Object>> fooList = jdbcTemplate.queryForList(sql,fooName);
		Integer.parseInt("ab2");
		/**
		 * fooList size为0,但不为空
		 */
		if(fooList != null){
			Map<String,Object> fooMap = fooList.get(0);
			Foo foo = new Foo();
			foo.setAge((Integer)fooMap.get("age"));
			foo.setName(fooMap.get("name").toString());
			return foo;
		}
		return null;
	}

	@Override
	public Foo getFoo(String fooName, String barName) {
		return null;
	}

	@Override
	public void insertFoo(Foo foo) {
		JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
		String sql  = "INSERT INTO stuff SET name=?,age=?";
		jdbcTemplate.update(sql,foo.getName(),foo.getAge());
		//事务回滚
		//throw new RuntimeException("DefaultFooService insertFoo Exception");
		
		
		//updateFoo抛出异常,整个事务回滚
		//updateFoo(foo);

		
		//try catch住exception后,整个事务正常提交
		/*try {
			updateFoo(foo);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/
		
		//在updateFoo内部try catch exception,整个事务正常提交
		updateFoo(foo);
		
	}

	@Override
	public void updateFoo(Foo foo) {
	
			try {
				JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
				String sql  = "update stuff SET name=?,age=?";
				jdbcTemplate.update(sql,foo.getName(),foo.getAge()+2);
				Integer.parseInt("2a");
			} catch (DataAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (NumberFormatException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		

	}

	@Override
	public void clear() {
		String sql = "delete from stuff";
		JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
		jdbcTemplate.execute(sql);
		
	}

}
